package utils.audit;

import org.hibernate.event.spi.PostUpdateEvent;
import org.hibernate.event.spi.PostUpdateEventListener;
import utils.AuditLogger;

public class PostUpdateEventListenerImpl  implements PostUpdateEventListener {

	@Override
	public void onPostUpdate(PostUpdateEvent event) {
		String entityName = event.getPersister().getEntityName();
		Long id = System.currentTimeMillis();

		String msg = String.format("update data:[%s(id=%s)]",entityName,event.getId());
		AuditLogger.auditGeneral(id,msg);

		int[] dirtyProperties = event.getDirtyProperties();
		Object[] oldState = event.getOldState();
		Object[] newState = event.getState();
		String [] fields = event.getPersister().getPropertyNames();
		for (int prop : dirtyProperties
			 ) {
			String old = oldState[prop]==null?"":oldState[prop].toString();
			String newString = newState[prop]==null?"":newState[prop].toString();
			AuditLogger.auditDetail(id,fields[prop], old ,newString);
		}
	}


}